﻿@page "/CultureRecouece/{Id?}"
@using AntDesign.TableModels
@using System.ComponentModel
@using System.Net.Http.Headers
@using Microsoft.Extensions.Logging
<PageContainer Title="CultureRecouece">
    <Spin Spinning="Spinning">
        <Card>
            <Body>
                <Flex Vertical="true">
                    <Divider Orientation="left">区域</Divider>
                    <Flex Wrap="wrap" Gap="small">
                        
                        <Tag Checkable Color="@PresetColor.Blue.ToString()" OnClick="ShowOpenCreateCultureModalModal">
                            <Icon Type="plus" />新增
                        </Tag>
                        
                        @foreach (var i in Cultures)
                        {
                            <Tooltip Title='@(SupportedCulture.ChineseLanguages[i.Name] + "-" + @SupportedCulture.EnglishLanguages[i.Name])'>
                                <Tag>@i.Name</Tag>
                            </Tooltip>
                        }
                    </Flex>
                    <Divider Orientation="left">资源</Divider>
                    <Flex Wrap="wrap" Gap="small" Style="margin-bottom:16px">
                        <Button Type="@ButtonType.Primary" OnClick="ShowOpenCreateResourceModalModal">
                             <Icon Type="plus" />新增
                         </Button>
                        <Button Type="@ButtonType.Primary" OnClick="ShowOpenUploadResourceModalModal">
                            <Icon Type="upload" Theme="outline" />上传文件
                         </Button>
                        <Button Type="@ButtonType.Primary" OnClick="ReloadData">
                            <Icon Type="reload" Theme="outline" />刷新
                         </Button>
                    </Flex>
                    <Table @ref="tableRef" TItem="IDictionary<string, Dto.CultureResourceDto>" DataSource="_data" Loading="_loading" Total="_total" OnChange="HandleTableChange" PageSize="20" RemoteDataSource RowKey='x=>x["key"].Value'
                            ScrollX="2500">
                         @foreach (var key in Columns)
                        {
                            if (key.DataIndex == "key")
                            {
                                <ActionColumn Title="Action" Width="100" Fixed="left">
                                    <a @onclick='() => DeleteResource(context["key"].Value)'>删除</a>
                                </ActionColumn>
                                <PropertyColumn Filterable Width="100" Fixed="left" Property=@(c=>c[key.DataIndex].Value) Title='@key.Title'   ></PropertyColumn>
                            }
                            else
                            {
                                <PropertyColumn Width="200" Property=@(c=>c[key.DataIndex].Value) Title='@string.Join("-", key.Title, key.ShortTitle)'>
                                    @if (editId == string.Join(",", context["key"].Value, key.DataIndex))
                                    {
                                        <Input Type="text" @bind-Value="context[key.DataIndex].Value" OnBlur="() => stopEdit(context[key.DataIndex].Value)" AutoFocus />
                                    }
                                    else
                                    {
                                        <div class="editable-cell-value-wrap" style="padding-right:24px" @onclick='()=>startEdit(string.Join(",", context["key"].Value, key.DataIndex))'>
                                            @context[key.DataIndex].Value
                                        </div>
                                    }
                                </PropertyColumn>
                            }
                        }
                    </Table>
                </Flex>
            </Body>
        </Card>
        <CreateCulture Visible="_visible" OnFinish="OnFinish" ProjectId="@Id">

        </CreateCulture>
        <CreateResource Visible="_resource_visible" OnFinish="OnResourceFinish" ProjectId="@Id">

        </CreateResource>
        <UploadResourceFile Visible="_UploadResource_visible" OnFinish="OnUploadResourceFinish" ProjectId="@Id">

        </UploadResourceFile>
    </Spin>
</PageContainer>

@code {
    [Parameter]
    public string? Id { get; set; }

    RenderFragment PageExtra() =>@<Button Type="dashed"><Icon Type="plus-circle" Theme="outline" />新增地区</Button>;

    IDictionary<string, (bool edit, IDictionary<string, Dto.CultureResourceDto> data)> editCache = new Dictionary<string, (bool edit, IDictionary<string, Dto.CultureResourceDto> data)>();
    List<IDictionary<string, Dto.CultureResourceDto>> listOfData = new();

    private bool Spinning = false;

    bool _loading = false;
    bool _visible { get; set; } = false;
    bool _resource_visible { get; set; } = false;
    bool _UploadResource_visible { get; set; } = false;
    int _total;


    string editId;

    IDictionary<string, Dto.CultureResourceDto>[] _data = { };
    Table<IDictionary<string, Dto.CultureResourceDto>> tableRef;
    Dto.CultureDto[] Cultures = { };

    [Inject] HttpClient Http { get; set; }
    [Inject] CultureClient CultureClient { get; set; }
    [Inject] ResourcesClient ResourcesClient { get; set; }
    [Inject] ILogger<Resources> Logger { get; set; }
    Dto.AntdColumn[] Columns = { };
    SupportedCulture SupportedCulture = new ();
    protected override async Task OnInitializedAsync()
    {
        Spinning = true;
        await base.OnInitializedAsync();
        await GetCulture();
        Spinning = false;
    }
    public ListGridType CultureGrid = new ListGridType { Gutter = 1, Column = 20 };
    async Task GetCulture()
    {
        var columnsData = await ResourcesClient.ColumnsAsync(Id);
        Columns = columnsData.Data.ToArray();
        var result = await CultureClient.CultureGETAsync(Id, 1, 99, "Id");
        Cultures = result.Data.ToArray();
    }
    async Task HandleTableChange(QueryModel<IDictionary<string, Dto.CultureResourceDto>> queryModel)
    {
        Spinning = true;
        _loading = true;
        var columnsData = await ResourcesClient.ColumnsAsync(Id).ConfigureAwait(false);
        Columns = columnsData.Data.ToArray();
        Logger.LogInformation(System.Text.Json.JsonSerializer.Serialize(queryModel));
        var resourcesData = await ResourcesClient.Project2Async(null, Id, queryModel.FilterModel.FirstOrDefault()?.SelectedValues?.FirstOrDefault(), queryModel.PageIndex, queryModel.PageSize, orderBy: "Id Desc").ConfigureAwait(false);
        _data = resourcesData.Data.ToArray();
        _total = int.Parse(resourcesData.Total);
        _loading = false;
        Spinning = false;
    }

    void ShowOpenCreateCultureModalModal()
    {
        _visible = true;
        _resource_visible = false;
        _UploadResource_visible = false;
    }
    
    void ShowOpenCreateResourceModalModal()
    {
        _resource_visible = true;
        _visible = false;
        _UploadResource_visible = false;
    }
    void ShowOpenUploadResourceModalModal()
    {
        _visible = false;
        _resource_visible = false;
        _UploadResource_visible = true;
    }

    private async Task OnFinish()
    {
        await GetCulture();
        tableRef.ReloadData();
        await Task.Delay(2000);
        _visible = false;
    }
    private async Task OnResourceFinish()
    {
        _resource_visible = false;
        await Task.Run(async () =>
        {
            await Task.Delay(2000);
            Spinning = true;
            tableRef.ReloadData();
            Spinning = false;
        });
    }
    private async Task OnUploadResourceFinish()
    {
        _UploadResource_visible = false;
        await Task.Run(async () =>
        {
            await Task.Delay(2000);
            Spinning = true;
            tableRef.ReloadData();
            Spinning = false;
        });
    }
    async Task DeleteResource(string key)
    {
        await ResourcesClient.ResourcesDELETEByKeyAsync(key, Id);
        Spinning = true;
        tableRef.ReloadData();
        Spinning = false;
    }

    void startEdit(string id)
    {
        editId = id;
    }
    void ReloadData()
    {
        _visible = false;
        _resource_visible = false;
        _UploadResource_visible = false;
        tableRef.ReloadData();
    }
    async Task stopEdit(string data)
    {
        var keys = editId.Split(",");
        Logger.LogInformation(editId);
        await ResourcesClient.ByCultureAndKeyAsync(new Dto.UpdateResourceByCultureAndKeyDto
        {
            Key = keys[0],
            Culture = keys[1],
            Value = data,
            Project = Id
        });
        editId = null;

        Spinning = true;
        tableRef.ReloadData();
        Spinning = false;
    }
}


<style>
    .editable-cell {
        position: relative;
    }

    .editable-cell-value-wrap {
        padding: 5px 12px;
        cursor: pointer;
    }

    .editable-row:hover .editable-cell-value-wrap {
        padding: 4px 11px;
        border: 1px solid #d9d9d9;
        border-radius: 4px;
    }

    [data-theme='dark'] .editable-row:hover .editable-cell-value-wrap {
        border: 1px solid #434343;
    }
</style>